import 'package:flutter/foundation.dart';
import 'package:loxen/api/api.dart';
import 'package:loxen/mode/material/material_index_bean.dart';
import 'package:loxen/mode/material/material_list_bean.dart';
import 'package:loxen/viewmode/base_view_model.dart';
import 'package:rxdart/rxdart.dart';

class MaterialIndexViewModel extends BaseViewModel {
  MaterialIndexBean _materialIndexBean;
  MaterialListBean _materialListBean;

  MaterialListBean get materialListBean => _materialListBean;

  MaterialIndexBean get materialIndexBean => _materialIndexBean;

  //加载素材首页
  void loadData() {
    if (mState == BaseState.LOADING) return;
    ApiService.materialIndex()
        .doOnListen(() {
          mState = BaseState.LOADING;
        })
        .flatMap(
            (value) => compute(decodeMaterialIndexBean, value.data).asStream())
        .flatMap((value) {
          _materialIndexBean = value;
          return ApiService.materialProduct();
        })
        .flatMap(
            (value) => compute(decodeMaterialListBean, value.data).asStream())
        .listen((event) {
          _materialListBean = event;
          mState = BaseState.CONTENT;
        }, onError: (error, stackTrace) {
          mState = BaseState.FAIL;
          print(error);
          print(stackTrace);
        }, onDone: () => notifyListeners());
  }

  static MaterialListBean decodeMaterialListBean(dynamic json) {
    return MaterialListBean.fromJson(json);
  }

  static MaterialIndexBean decodeMaterialIndexBean(dynamic json) {
    return MaterialIndexBean.fromJson(json);
  }
}
